/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Defects, IssueReport, MatcherCallback, MatcherTypes, MethodMatcher, Rule } from '../../Index';
import { ArkAssignStmt, ArkIfStmt, ArkInstanceFieldRef, ArkMethod, ArkNormalBinopExpr, FieldSignature, Local, Value } from 'arkanalyzer';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'OptionalConditionChainingCheck');
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/optional-condition-chaining-check.md',
    description: 'Simplify null checks with optional chaining'
};

export class OptionalConditionChainingCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private mtdMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD
    };

    public registerMatchers(): MatcherCallback[] {
        const matchMethodCb: MatcherCallback = {
            matcher: this.mtdMatcher,
            callback: this.check
        };
        return [matchMethodCb];
    }

    public check = (target: ArkMethod): void => {
        const desiredStmts: FieldSignature[] = [];
        const stmts = target.getBody()?.getCfg().getStmts() ?? [];
        const ifStmts = stmts.filter((stmt): stmt is ArkIfStmt => stmt instanceof ArkIfStmt);
        for (let stmt of ifStmts) {
            const op = stmt.getConditionExpr().getOp1();
            const rightOp = this.processOp(op);
            if (!rightOp) {
                continue;
            }
            if (rightOp instanceof ArkInstanceFieldRef) {
                this.isArkInstanceFieldRef(rightOp, desiredStmts);
            }
            if (rightOp instanceof ArkNormalBinopExpr) {
                this.isArkNormalBinopExpr(rightOp, rightOp.getOp1(), desiredStmts);
            }
            if (desiredStmts.length === 2 && desiredStmts[0] === desiredStmts[1]) {
                this.reportIssue(stmt, '.' + desiredStmts[0].getFieldName());
            }
        }
    };

    private isArkNormalBinopExpr(rightOp: ArkNormalBinopExpr, op: Value, desiredStmts: FieldSignature[]): void {
        const rightOp2 = this.processOp(op);
        if (rightOp2 instanceof ArkInstanceFieldRef) {
            this.isArkInstanceFieldRef(rightOp2, desiredStmts);
            const rightOp3 = this.processOp(rightOp.getOp2());
            if (rightOp3 && rightOp3 instanceof ArkInstanceFieldRef) {
                this.isArkInstanceFieldRef(rightOp3, desiredStmts);
            }
        } else if (rightOp2 instanceof ArkNormalBinopExpr) {
            this.isArkNormalBinopExpr(rightOp2, rightOp2.getOp1(), desiredStmts);
        }
    }

    private isArkInstanceFieldRef(rightOp: ArkInstanceFieldRef, desiredStmts: FieldSignature[]): void {
        const base = rightOp.getBase();
        if (base.getName() === 'this') {
            desiredStmts.length = 0;
            desiredStmts.push(rightOp.getFieldSignature());
        }
        if (base.getName().includes('%')) {
            const rightOp = this.processOp(base);
            if (rightOp && rightOp instanceof ArkInstanceFieldRef) {
                desiredStmts.push(rightOp.getFieldSignature());
            }
        }
    }

    private processOp(op: Value): Value | null {
        if (!(op instanceof Local)) {
            return null;
        }
        const declaringStmt = op.getDeclaringStmt();
        if (!(declaringStmt && declaringStmt instanceof ArkAssignStmt)) {
            return null;
        }
        return declaringStmt.getRightOp();
    }

    private reportIssue(stmt: ArkIfStmt, keyword: string): void {
        const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile();
        const severity = this.rule.alert ?? this.metaData.severity;
        const text = stmt.getOriginalText();
        if (!text || text.length === 0) {
            return;
        }
        const originalPosition = stmt.getOriginPositionInfo();
        const lineNum = originalPosition.getLineNo();
        const startCol = originalPosition.getColNo() + text.indexOf(keyword);
        const endCol = startCol + keyword.length;
        const filePath = arkFile.getFilePath();
        let defects = new Defects(lineNum, startCol, endCol, this.metaData.description, severity, this.rule.ruleId,
            filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}
